package com.wm.machine.baselibrary.common.widget.recyclerview.itemdecoration;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Copyright
 * author zhengcheng
 * date 2018/2/12
 * describe
 * history
 */

public class GridEntrust extends RecyclerView.ItemDecoration {
  private int leftRight;
  private int topBottom;
  private int mColor = 0;
  private Paint mPaint;

  public GridEntrust(int leftRight, int topBottom, int mColor) {
    this.leftRight = leftRight;
    this.topBottom = topBottom;
    this.mColor = mColor;
    mPaint = new Paint();
    mPaint.setColor(mColor);
  }

  @Override
  public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
    super.onDraw(c, parent, state);
    int left;
    int top;
    int right;
    int bottom;
    GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
    int childCount = layoutManager.getChildCount();
    for (int i = 0; i < childCount; i++) {
      View child = parent.getChildAt(i);
      left = child.getLeft();
      top = child.getBottom();
      right = child.getRight();
      bottom = top + topBottom;
      c.drawRect(left, top, right, bottom, mPaint);
      left = child.getRight();
      top = child.getTop();
      right = left + leftRight;
      bottom = child.getBottom() + topBottom;
      c.drawRect(left, top, right, bottom, mPaint);
    }
  }

  @Override
  public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    super.getItemOffsets(outRect, view, parent, state);
    GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
    GridLayoutManager.LayoutParams layoutParams =
            (GridLayoutManager.LayoutParams) view.getLayoutParams();
    int childPosition = parent.getChildAdapterPosition(view);
    if (layoutManager.getOrientation() == GridLayoutManager.VERTICAL) {
      if (layoutParams.getSpanIndex() != 0) {
        outRect.left = leftRight;
      }
      if (childPosition > layoutManager.getSpanCount() - 1) {
        outRect.top = topBottom;
      }
    } else {
      if (childPosition > layoutManager.getSpanCount() - 1) {
        outRect.left = leftRight;
      }
      outRect.bottom = topBottom;
    }
  }

}

